package com.example.demo.action.client;/**
 * Created by kete on 2018-11-30.
 */

import com.example.demo.action.common.CustomProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 作者：kete
 * 创建时间：2018-11-30 16:30
 * 功能描述：
 * 版本：
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final static Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;

            if(event.state() == IdleState.WRITER_IDLE){
                logger.info("已经 10 秒没有发送信息！");
                CustomProtocol customProtocol = SpringBeanFactory.getBean(CustomProtocol.class);
                ctx.writeAndFlush(customProtocol).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {

        logger.info("来自服务端消息:"+byteBuf.toString(CharsetUtil.UTF_8));
    }
}
